package com.zzh.lib.views.adapter;


import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

/**
 * Created by ZZH on 2023/2/16.
 *
 * @date: 2023/2/16 14:10
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.lib.views.adapter
 */
public abstract class HBaseViewPagerAdapter<T> extends PagerAdapter {
    Context context;

    public HBaseViewPagerAdapter(Context context) {
        this.context = context;
    }

    private List<T> dataList = new ArrayList();

    protected abstract View getItemView(Context context, T data, int position);

    public int getCount() {
        if (dataList.size() <= 1) {
            return dataList.size();
        } else {
            return Integer.MAX_VALUE;
        }
    }

    public int getListSize() {
        return dataList.size();
    }

    public void setNewInstance(Collection<? extends T> data) {
        if (data == null) {
            dataList.clear();
        } else {
            dataList.clear();
            dataList.addAll(data);
        }
        notifyDataSetChanged();
    }

    public void addData(T data) {
        dataList.add(data);
        notifyDataSetChanged();
    }

    public void addData(Collection<? extends T> data) {
        dataList.addAll(data);
        notifyDataSetChanged();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int p = position % dataList.size();
        T data = dataList.get(p);
        View view = getItemView(context, data, position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
